package com.phkj.qdh.utils.treela;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;

import java.util.List;

/**
 * Created by keranbin on 2016/8/30.
 */
public abstract class TreeListViewAdapter<T> extends BaseAdapter implements AdapterView.OnItemClickListener {
    protected Context context;
    protected ListView listView;
    protected List<Node> mAllNodes;
    protected List<Node> mVisibleNodes;
    protected LayoutInflater inflater;

    private OnTreeNodeClickListener onTreeNodeClickListener;

    public TreeListViewAdapter(Context context, ListView listView, List<T> datas, int defaultExpandLevel) throws IllegalAccessException {
        this.context = context;
        this.listView = listView;
        mAllNodes = TreeHelp.getSortedNodes(datas,defaultExpandLevel);
        mVisibleNodes = TreeHelp.filterVisibleNodes(mAllNodes);
        inflater = LayoutInflater.from(context);
        listView.setOnItemClickListener(this);
    }

    @Override
    public int getCount() {
        return mVisibleNodes.size();
    }

    @Override
    public Object getItem(int position) {
        return mVisibleNodes.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        Node node=mVisibleNodes.get(position);
        view=getConvertView(node,position,view,viewGroup);
        //设置内边距
        view.setPadding(30*node.getLevel(),3,3,3);
        return view;
    }


    /**
     * 设置点击展开或者收缩
     *
     * @param position
     */
    private void expandOrCollapse(int position) {
        Node node = mVisibleNodes.get(position);
        if (node != null) {
            if (node.isLeft())
                return;
            node.setExpand(!node.isExpand());
            mVisibleNodes=TreeHelp.filterVisibleNodes(mAllNodes);
            notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        expandOrCollapse(position);
        if (onTreeNodeClickListener!=null){
            onTreeNodeClickListener.setOnClick(mVisibleNodes.get(position),position);
        }
    }

    public void setOnTreeNodeClickListener(OnTreeNodeClickListener onTredNodeClickListener){
        this.onTreeNodeClickListener=onTredNodeClickListener;
    }

    /**
     * 设置node的点击回调
     */
    public interface OnTreeNodeClickListener{
        void setOnClick(Node node, int position);
    }

    public abstract View getConvertView(Node node,int position, View view, ViewGroup viewGroup);
}